//	 Copyright 2011 Elian ORIOU
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package org.eo.geomapper.validator;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * The GeoMapper Validator. It validates the structure of the XML configuration
 * provided by user, using an XML Schema.
 * 
 * @author Elian ORIOU
 * 
 */

public class GeoMapperValidator {

	private static final String SCHEMA_PATH = "schema/geomap.xsd";
	private static final String XML_SCHEMA_MODEL_URL = "http://www.w3.org/2001/XMLSchema";
	private boolean isValidated;

	public GeoMapperValidator() {
		isValidated = true;
	}

	/**
	 * Returns true if the XML configuration file is well formed and well
	 * structured, false otherwise
	 * 
	 * @param file
	 *            The XML configuration file
	 * @return the validation result
	 */

	public boolean validate(File file) {

		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();

			SchemaFactory schemaFactory = SchemaFactory
					.newInstance(XML_SCHEMA_MODEL_URL);
			factory.setSchema(schemaFactory
					.newSchema(new Source[] { new StreamSource(getClass().getResource(SCHEMA_PATH).toString()) }));

			DocumentBuilder builder = factory.newDocumentBuilder();
			builder.setErrorHandler(new org.xml.sax.ErrorHandler() {
				public void fatalError(SAXParseException exception)
						throws SAXException {
					isValidated = false;
				}

				public void error(SAXParseException e) throws SAXParseException {
					System.out.println("Error at line " + e.getLineNumber()
							+ " : " + e.getMessage());
					isValidated = false;
				}

				public void warning(SAXParseException err)
						throws SAXParseException {
				}
			});

			builder.parse(new FileInputStream(file));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		return isValidated;
	}
}